package com.me.study.app.rvRichEditor.provider

import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import cn.jzvd.Jzvd
import cn.jzvd.JzvdStd
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.me.study.R
import com.me.study.app.data.RichEditorType
import com.me.study.app.ext.load
import com.me.study.app.rvRichEditor.RichEditorData
import com.me.study.app.rvRichEditor.listener.EditorTouchListener
import com.me.study.weight.JZMediaExo

class RichEditorVideoProvider(private val listener: EditorTouchListener) : BaseItemProvider<RichEditorData>() {

    override val itemViewType = RichEditorType.VIDEO.VALUE

    override val layoutId = R.layout.peovider_rich_editor_video

    override fun convert(helper: BaseViewHolder, item: RichEditorData) {
        val viewMove = helper.getView<ImageView>(R.id.iv_move)
        helper.getView<JzvdStd>(R.id.JzvdStd).apply {
            setUp(item.s1, "", Jzvd.SCREEN_NORMAL, JZMediaExo::class.java)
        }
        helper.getView<ImageView>(R.id.image_video_cover).apply {
            load(context, item.s1) {
                item.coverBitmap = it
                Glide.with(context).load(it).into(this)
            }
        }
        val textWatcher = InputTextWatcher(item)
        val content = item.s2
        val view = helper.getView<EditText>(R.id.ed_input)
        view.setText(content)
        view.setSelection(content.length)
        view.clearFocus()
        if (view.tag != null) {
            view.removeTextChangedListener(textWatcher)
            view.tag = null
        }
        view.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                view.addTextChangedListener(textWatcher)
                view.tag = textWatcher
            } else {
                view.removeTextChangedListener(textWatcher)
                view.tag = null
            }
        }
        viewMove.setOnTouchListener { p0, p1 ->
            when (p1.action) {
                MotionEvent.ACTION_DOWN -> {
                    listener.onItemDown(helper)
                }
            }
            true
        }
    }

    inner class InputTextWatcher(private var item: RichEditorData) : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable?) {
            if (s.toString().isNotEmpty()) {
                item.s2 = s.toString()
            } else {
                item.s2 = ""
            }
        }
    }
}